using System.IO;

namespace System.Xml.Serialization
{
    using System.Runtime.Serialization.Formatters.Binary;
    using Internal;

    [Serializable]
    public class XmlBinaryStreamSerializer<T> : XmlStreamSerializer<T>
    {
        protected override MemoryStream InternalStreamSerialize(T obj, IXmlTypeFormatter formatter)
        {
            try
            {
                IXmlRuntimeSerializerInternal serializer = XmlRuntimeHelper.GetSerializer(typeof(T), formatter);
                if (serializer != null)
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    MemoryStream ms = new MemoryStream();
                    binaryFormatter.Serialize(ms, obj);
                    return ms;
                }
                return null;
            }
            catch (Exception ex)
            {
                throw new XmlSerializationException();
                //PluginLog.WriteErrorSync(ex);
            }
        }

        protected override T InternalStreamDeserialize(MemoryStream input, IXmlTypeFormatter formatter)
        {
            try
            {
                IXmlRuntimeSerializerInternal serializer = XmlRuntimeHelper.GetSerializer(typeof(T), formatter);
                if (serializer != null)
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(input);
                }
            }
            catch (Exception ex)
            {
                throw new XmlSerializationException();
                //PluginLog.WriteErrorSync(ex);
            }
            return default(T);
        }
    }
}


